package com.probiz.estoresa.catalog.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.catalog.model.GiftCategoryFullyModel;
import com.probiz.estore.catalog.service.GiftCategoryManager;
import com.probiz.estore.common.model.catalog.GiftCategory;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.webapp.util.RequestUtil;

public class GiftCategoryController extends GenericStoreAdminController<GiftCategory> {
	private GiftCategoryManager	giftCategoryManager	= null;

	public void setGiftCategoryManager(GiftCategoryManager inMgr) {
		this.giftCategoryManager = inMgr;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericStoreAdminController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(GiftCategory entity) {
		return entity.getGiftCategoryName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericStoreAdminController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = giftCategoryManager;
	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("catalog/giftCategoryList");
		GiftCategory treeRoot = giftCategoryManager.getById(1);
		Set<GiftCategory> categorySet = treeRoot.getChildren();
		List<GiftCategory> categoryList = new ArrayList<GiftCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList", categoryList);
		mv.addObject("treeRoot", treeRoot);
		return mv;
	}

	/**
	 * 获取树节点，ajax方式
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getTreeItems(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView(
				"/catalog/include/giftCategoryTreeAjax");
		String categoryId = RequestUtil.getParameterNullSafe(request,
				"categoryId");
		GiftCategory parent = giftCategoryManager.getById(Integer
				.valueOf(categoryId));
		Set<GiftCategory> categorySet = parent.getChildren();
		List<GiftCategory> categoryList = new ArrayList<GiftCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList", categoryList);
		return mv;

	}

	/**
	 * 按categoryIds的顺序更新目录sortOrder
	 */
	public ModelAndView updateCategoriesSortOrder(HttpServletRequest request,
			HttpServletResponse response) {
		Integer[] categoryIds = RequestUtil.getIntegerArrayNullSafe(request,
				"categoryIds");
		// MethodUtils.invokeMethod(mgr, "updateCategoriesSortOrder", new
		// Object[]{categoryIds});
		giftCategoryManager.updateCategoriesSortOrder(categoryIds);
		return null;
	}

	/**
	 * 按categoryId删除目录
	 */
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer categoryId = RequestUtil.getInteger(request, "categoryId");
		GiftCategory giftCategory = giftCategoryManager.getById(categoryId);
		Map<String, Object> data = giftCategoryManager
				.deleteFully(giftCategory);
		return getModelAndAjaxJsonView(data);

	}

	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("catalog/giftCategoryForm");

		Integer categoryId = RequestUtil.getInteger(request, "categoryId");
		if (null != categoryId) {
			// case:编辑
			GiftCategory category = giftCategoryManager.getById(categoryId);
			mv.addObject("category", category);
		} else {
			// case:新增
			Integer parentCategoryId = RequestUtil.getInteger(request,
					"parentCategoryId");
			GiftCategory parentCategory = giftCategoryManager
					.getById(parentCategoryId);
			mv.addObject("parentCategory", parentCategory);
			GiftCategory category = new GiftCategory();
			category.setParent(parentCategory);
			mv.addObject("category", category);
		}

		return mv;
	}

	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) {
		return edit(request, response);
	}

	/**
	 * 前置绑定，避免验证错误
	 * 
	 * @param entity
	 *            实体
	 */
	private void bindReady(GiftCategory entity) {
		if (null == entity.getCategoryId()) {
			// case:新增
			entity.setSortOrder(GiftCategory.SORTORDER_DEFAULT_VALUE);
		}
	}
	
	/*
	 * 保存前的检验和赋值
	 */
	protected void preSave(HttpServletRequest request, GiftCategory entity,
			BindException errors) {
		// start:赋值dispalyFlag
		String[] displayFlagArray = RequestUtil.getParameterValuesNullSafe(
				request, "displayFlag");
		StringBuffer displayFlag = new StringBuffer();
		for (String flag : displayFlagArray) {
			displayFlag.append(flag);
		}
		entity.setDisplayFlag(displayFlag.toString());
		// end:赋值dispalyFlag
	}

	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// 取得Form对应的Model
		GiftCategory entity = formBackingObject(request);
		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				Map<String, Object> saveData = giftCategoryManager
						.saveFully(getGiftCategoryModel(request, entity, data));
				data.putAll(saveData);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		buildReturnInfo(data, entity, request);

		return getModelAndAjaxJsonView(data);
	}

	/**
	 * 加入返回参数
	 * 
	 * @param data
	 * @param gift
	 * @param request
	 */
	private void buildReturnInfo(Map<String, Object> data, GiftCategory entity,
			HttpServletRequest request) {
		data.put("categoryId", entity.getCategoryId());
		data.put("categoryName", entity.getCategoryName());
		data.put("categoryCode", entity.getCategoryCode());
		data.put("depth", entity.getDepth());
		data.put("itemCount", entity.getItemCount());
		data.put("activeItemCount", entity.getActiveItemCount());
	}

	// 构造模型，方便保存
	private GiftCategoryFullyModel getGiftCategoryModel(
			HttpServletRequest request, GiftCategory entity,
			Map<String, Object> data) {
		GiftCategoryFullyModel model = new GiftCategoryFullyModel();

		model.setGiftCategory(entity);

		return model;
	}
}
